package com.dcdata.jt809server.protocol.encode;

import com.dcdata.jt809server.common.util.CommonUtils;
import com.dcdata.jt809server.common.util.PacketDecoderUtils;
import com.dcdata.jt809server.common.util.PacketEncoderUtils;
import com.dcdata.jt809server.packet.BasePacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * program: JT809Server
 * description: 编码器
 * @author DCDATA
 * @date 2020-03-19 11:41
 **/
@Slf4j
public class TrafficEncodeAdapter extends MessageToByteEncoder<BasePacket> {

    @Override
    protected void encode(ChannelHandlerContext ctx, BasePacket msg, ByteBuf out) {
        log.debug("进行报文发送处理");
        byte[] allBody = msg.getAllBody();
        // 转义
        byte[] dataBytes = PacketEncoderUtils.encoderEscape(allBody);
        byte[] bytes1 = CommonUtils.append(new byte[]{BasePacket.HEAD_FLAG}, dataBytes);
        byte[] bytes = CommonUtils.append(bytes1, new byte[]{BasePacket.END_FLAG});
        String hexStr = PacketDecoderUtils.bytes2HexStr(bytes);
        log.info("发出的报文为：{}", hexStr);
        out.writeBytes(bytes);
    }
}
